package com.project.RocketRoute.executor;

import com.project.RocketRoute.model.RocketRouteBean;
import com.project.annotation.rocket.RocketRoute;
import com.project.annotation.rocket.RouteMethod;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

@Component
public class RocketRouteSetting implements ApplicationContextAware {

    private static ApplicationContext applicationValue;
    private static Map<String, List<RocketRouteBean>> serverContext = new HashMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationcontext)
            throws BeansException {
        applicationValue = applicationcontext;
        String[] beanNamesForAnnotation = applicationcontext.getBeanNamesForAnnotation(RocketRoute.class);
        for(String entry : beanNamesForAnnotation){
            Class<?> type = applicationcontext.getType(entry);
            Method[] methods = type.getMethods();
            for (Method m : methods){
                if (m.isAnnotationPresent(RouteMethod.class)){
                    RouteMethod val = m.getAnnotation(RouteMethod.class);
                    RocketRouteBean rocketRoutBean = new RocketRouteBean();
                    rocketRoutBean.setBean(applicationcontext.getBean(entry));
                    rocketRoutBean.setMethod(m);
                    rocketRoutBean.setAsync(val.async());
                    rocketRoutBean.setClassName(val.className());
                    rocketRoutBean.setResult(val.next());
                    rocketRoutBean.setRouteMethod(val);
                    rocketRoutBean.setName(String.format("%s.%s", val.topic(), val.tags()));
                    System.out.println("==============>rocket find name: " + rocketRoutBean.getName());
                    if (!serverContext.containsKey(rocketRoutBean.getName())){
                        serverContext.put(rocketRoutBean.getName(), new ArrayList<>());
                    }
                    serverContext.get(rocketRoutBean.getName()).add(rocketRoutBean);
                }
            }
        }
    }

    public static Class<?> getBeanType(String name){
        return applicationValue.getType(name);
    }

    public static List<RocketRouteBean> getBean(String name) throws InvocationTargetException, IllegalAccessException {
        if (serverContext.containsKey(name)) {
            return serverContext.get(name);
        }
        return null;
    }

    public static Map<String, List<RocketRouteBean>> getBeans(){
        return serverContext;
    }
}
